<template>
  <div class="performance-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>系统性能优化</h3>
          <div class="header-actions">
            <el-button type="primary" @click="runOptimization">
              <el-icon><Lightning /></el-icon>
              执行优化
            </el-button>
            <el-button type="success" @click="generateReport">
              <el-icon><Document /></el-icon>
              生成报告
            </el-button>
            <el-button type="info" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 性能概览 -->
      <div class="performance-overview">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ performanceStats.avgResponseTime }}ms</div>
                <div class="overview-label">平均响应时间</div>
                <div class="overview-trend" :class="performanceStats.responseTrend < 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="performanceStats.responseTrend < 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(performanceStats.responseTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ performanceStats.throughput }}</div>
                <div class="overview-label">吞吐量 (req/s)</div>
                <div class="overview-trend" :class="performanceStats.throughputTrend > 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="performanceStats.throughputTrend > 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(performanceStats.throughputTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ performanceStats.errorRate }}%</div>
                <div class="overview-label">错误率</div>
                <div class="overview-trend" :class="performanceStats.errorTrend < 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="performanceStats.errorTrend < 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(performanceStats.errorTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="overview-content">
                <div class="overview-number">{{ performanceStats.uptime }}%</div>
                <div class="overview-label">系统可用性</div>
                <div class="overview-trend" :class="performanceStats.uptimeTrend > 0 ? 'up' : 'down'">
                  <el-icon><ArrowUp v-if="performanceStats.uptimeTrend > 0" /><ArrowDown v-else /></el-icon>
                  {{ Math.abs(performanceStats.uptimeTrend) }}%
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 性能分析标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="性能分析" name="analysis">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>响应时间趋势</span>
                  </template>
                  <div class="chart-container">
                    <v-chart
                      :option="responseTimeChartOption"
                      style="height: 300px; width: 100%;"
                      autoresize
                    />
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>吞吐量趋势</span>
                  </template>
                  <div class="chart-container">
                    <v-chart
                      :option="throughputChartOption"
                      style="height: 300px; width: 100%;"
                      autoresize
                    />
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="性能瓶颈" name="bottlenecks">
          <div class="tab-content">
            <el-table :data="bottlenecks" stripe>
              <el-table-column prop="type" label="瓶颈类型" width="150" />
              <el-table-column prop="description" label="描述" min-width="200" />
              <el-table-column prop="impact" label="影响程度" width="120">
                <template #default="{ row }">
                  <el-tag :type="getImpactType(row.impact)">
                    {{ row.impact }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="recommendation" label="优化建议" min-width="300" />
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="applyOptimization(row)">
                    应用优化
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="缓存管理" name="cache">
          <div class="tab-content">
            <div class="cache-controls">
              <el-button type="primary" @click="clearAllCache">
                <el-icon><Delete /></el-icon>
                清空所有缓存
              </el-button>
              <el-button type="success" @click="warmupCache">
                <el-icon><Lightning /></el-icon>
                预热缓存
              </el-button>
              <el-button type="info" @click="refreshCacheStats">
                <el-icon><Refresh /></el-icon>
                刷新统计
              </el-button>
            </div>
            
            <el-table :data="cacheStats" stripe>
              <el-table-column prop="name" label="缓存名称" width="200" />
              <el-table-column prop="type" label="缓存类型" width="150" />
              <el-table-column prop="size" label="缓存大小" width="120" />
              <el-table-column prop="hitRate" label="命中率" width="120">
                <template #default="{ row }">
                  <el-progress
                    :percentage="row.hitRate"
                    :color="getHitRateColor(row.hitRate)"
                    :stroke-width="8"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="lastUpdate" label="最后更新" width="180" />
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="clearCache(row)">
                    清空
                  </el-button>
                  <el-button type="success" size="small" @click="warmupCacheItem(row)">
                    预热
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="数据库优化" name="database">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>慢查询分析</span>
                  </template>
                  <el-table :data="slowQueries" stripe>
                    <el-table-column prop="query" label="查询语句" min-width="200" show-overflow-tooltip />
                    <el-table-column prop="executionTime" label="执行时间" width="120">
                      <template #default="{ row }">
                        <el-tag :type="getExecutionTimeType(row.executionTime)">
                          {{ row.executionTime }}ms
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="count" label="执行次数" width="100" />
                  </el-table>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <span>索引使用情况</span>
                  </template>
                  <el-table :data="indexUsage" stripe>
                    <el-table-column prop="table" label="表名" width="150" />
                    <el-table-column prop="index" label="索引名" width="150" />
                    <el-table-column prop="usage" label="使用率" width="120">
                      <template #default="{ row }">
                        <el-progress
                          :percentage="row.usage"
                          :color="getUsageColor(row.usage)"
                          :stroke-width="8"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="recommendation" label="建议" min-width="150" />
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="资源监控" name="resources">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card>
                  <template #header>
                    <span>CPU使用率</span>
                  </template>
                  <div class="resource-chart">
                    <v-chart
                      :option="cpuChartOption"
                      style="height: 200px; width: 100%;"
                      autoresize
                    />
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card>
                  <template #header>
                    <span>内存使用率</span>
                  </template>
                  <div class="resource-chart">
                    <v-chart
                      :option="memoryChartOption"
                      style="height: 200px; width: 100%;"
                      autoresize
                    />
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card>
                  <template #header>
                    <span>磁盘使用率</span>
                  </template>
                  <div class="resource-chart">
                    <v-chart
                      :option="diskChartOption"
                      style="height: 200px; width: 100%;"
                      autoresize
                    />
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, GaugeChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册必要的组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GaugeChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const activeTab = ref('analysis')

// 性能统计
const performanceStats = reactive({
  avgResponseTime: 245,
  responseTrend: -15.2,
  throughput: 1250,
  throughputTrend: 8.3,
  errorRate: 0.8,
  errorTrend: -25.0,
  uptime: 99.9,
  uptimeTrend: 0.1
})

// 性能瓶颈数据
const bottlenecks = ref([
  {
    type: '数据库查询',
    description: '用户列表查询响应时间过长',
    impact: '高',
    recommendation: '添加索引，优化查询语句，使用分页查询'
  },
  {
    type: '缓存命中率',
    description: '商品信息缓存命中率偏低',
    impact: '中',
    recommendation: '增加缓存预热，调整缓存策略，优化缓存键设计'
  },
  {
    type: '内存使用',
    description: '系统内存使用率持续偏高',
    impact: '中',
    recommendation: '优化内存使用，增加垃圾回收频率，考虑内存扩容'
  }
])

// 缓存统计
const cacheStats = ref([
  {
    name: '用户信息缓存',
    type: 'Redis',
    size: '2.5MB',
    hitRate: 85,
    lastUpdate: '2024-01-15 10:00:00'
  },
  {
    name: '商品信息缓存',
    type: 'Redis',
    size: '15.8MB',
    hitRate: 72,
    lastUpdate: '2024-01-15 09:45:00'
  },
  {
    name: '订单状态缓存',
    type: 'Memory',
    size: '1.2MB',
    hitRate: 95,
    lastUpdate: '2024-01-15 10:05:00'
  }
])

// 慢查询数据
const slowQueries = ref([
  {
    query: 'SELECT * FROM users WHERE status = ? ORDER BY create_time DESC',
    executionTime: 1250,
    count: 15
  },
  {
    query: 'SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id',
    executionTime: 890,
    count: 8
  },
  {
    query: 'SELECT COUNT(*) FROM orders WHERE create_time BETWEEN ? AND ?',
    executionTime: 650,
    count: 25
  }
])

// 索引使用情况
const indexUsage = ref([
  {
    table: 'users',
    index: 'idx_status',
    usage: 85,
    recommendation: '索引使用良好'
  },
  {
    table: 'products',
    index: 'idx_category_id',
    usage: 45,
    recommendation: '考虑优化查询条件'
  },
  {
    table: 'orders',
    index: 'idx_create_time',
    usage: 92,
    recommendation: '索引使用良好'
  }
])

// 图表配置
const responseTimeChartOption = computed(() => {
  const hours = []
  const responseTime = []
  
  for (let i = 0; i < 24; i++) {
    hours.push(`${i}:00`)
    responseTime.push(Math.floor(Math.random() * 200) + 100)
  }
  
  return {
    title: {
      text: '24小时响应时间',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hours
    },
    yAxis: {
      type: 'value',
      name: '响应时间(ms)'
    },
    series: [
      {
        name: '响应时间',
        type: 'line',
        smooth: true,
        data: responseTime,
        itemStyle: { color: '#409EFF' }
      }
    ]
  }
})

const throughputChartOption = computed(() => {
  const hours = []
  const throughput = []
  
  for (let i = 0; i < 24; i++) {
    hours.push(`${i}:00`)
    throughput.push(Math.floor(Math.random() * 500) + 800)
  }
  
  return {
    title: {
      text: '24小时吞吐量',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hours
    },
    yAxis: {
      type: 'value',
      name: '请求数/秒'
    },
    series: [
      {
        name: '吞吐量',
        type: 'bar',
        data: throughput,
        itemStyle: { color: '#67C23A' }
      }
    ]
  }
})

const cpuChartOption = computed(() => {
  return {
    series: [
      {
        name: 'CPU使用率',
        type: 'gauge',
        center: ['50%', '60%'],
        radius: '80%',
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: {
          lineStyle: {
            width: 8,
            color: [
              [0.3, '#67C23A'],
              [0.7, '#E6A23C'],
              [1, '#F56C6C']
            ]
          }
        },
        pointer: {
          itemStyle: { color: 'auto' }
        },
        axisTick: {
          distance: -30,
          splitNumber: 5,
          lineStyle: { width: 2, color: '#999' }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: { width: 4, color: '#999' }
        },
        axisLabel: {
          color: 'auto',
          distance: 40,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}%',
          color: 'auto',
          fontSize: 20
        },
        data: [{ value: 45 }]
      }
    ]
  }
})

const memoryChartOption = computed(() => {
  return {
    series: [
      {
        name: '内存使用率',
        type: 'gauge',
        center: ['50%', '60%'],
        radius: '80%',
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: {
          lineStyle: {
            width: 8,
            color: [
              [0.3, '#67C23A'],
              [0.7, '#E6A23C'],
              [1, '#F56C6C']
            ]
          }
        },
        pointer: {
          itemStyle: { color: 'auto' }
        },
        axisTick: {
          distance: -30,
          splitNumber: 5,
          lineStyle: { width: 2, color: '#999' }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: { width: 4, color: '#999' }
        },
        axisLabel: {
          color: 'auto',
          distance: 40,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}%',
          color: 'auto',
          fontSize: 20
        },
        data: [{ value: 62 }]
      }
    ]
  }
})

const diskChartOption = computed(() => {
  return {
    series: [
      {
        name: '磁盘使用率',
        type: 'gauge',
        center: ['50%', '60%'],
        radius: '80%',
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: {
          lineStyle: {
            width: 8,
            color: [
              [0.3, '#67C23A'],
              [0.7, '#E6A23C'],
              [1, '#F56C6C']
            ]
          }
        },
        pointer: {
          itemStyle: { color: 'auto' }
        },
        axisTick: {
          distance: -30,
          splitNumber: 5,
          lineStyle: { width: 2, color: '#999' }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: { width: 4, color: '#999' }
        },
        axisLabel: {
          color: 'auto',
          distance: 40,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value}%',
          color: 'auto',
          fontSize: 20
        },
        data: [{ value: 38 }]
      }
    ]
  }
})

// 方法
const handleTabChange = (tab) => {
  activeTab.value = tab
}

const getImpactType = (impact) => {
  const typeMap = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return typeMap[impact] || 'info'
}

const getHitRateColor = (rate) => {
  if (rate >= 90) return '#67C23A'
  if (rate >= 70) return '#E6A23C'
  return '#F56C6C'
}

const getExecutionTimeType = (time) => {
  if (time >= 1000) return 'danger'
  if (time >= 500) return 'warning'
  return 'success'
}

const getUsageColor = (usage) => {
  if (usage >= 80) return '#67C23A'
  if (usage >= 50) return '#E6A23C'
  return '#F56C6C'
}

const applyOptimization = (bottleneck) => {
  ElMessage.success(`正在应用优化：${bottleneck.recommendation}`)
}

const clearAllCache = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有缓存吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('所有缓存已清空')
  } catch {
    // 用户取消操作
  }
}

const warmupCache = () => {
  ElMessage.success('缓存预热已开始')
}

const refreshCacheStats = () => {
  ElMessage.success('缓存统计已刷新')
}

const clearCache = (cache) => {
  ElMessage.success(`缓存 ${cache.name} 已清空`)
}

const warmupCacheItem = (cache) => {
  ElMessage.success(`缓存 ${cache.name} 预热已开始`)
}

const runOptimization = () => {
  ElMessage.success('系统优化已开始执行')
}

const generateReport = () => {
  ElMessage.success('性能报告已生成')
}

const refreshData = () => {
  ElMessage.success('数据已刷新')
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.performance-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.performance-overview {
  margin-bottom: 30px;
}

.overview-card {
  text-align: center;
}

.overview-content {
  padding: 20px 0;
}

.overview-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.overview-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.overview-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.overview-trend.up {
  color: #67C23A;
}

.overview-trend.down {
  color: #F56C6C;
}

.tab-content {
  margin-top: 20px;
}

.chart-container {
  min-height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cache-controls {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.resource-chart {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
